#!/usr/bin/env php
<?php
$DBHOST='localhost';    //modify dbhost
$DBUSER='root';         //modify dbuser
$DBPASS='';             //modify dbpass
$DBNAME='svnpub';       //modify dbname

$REPOS=$_SERVER['argv'][1];
$REV=$_SERVER['argv'][2];
$SVNLOOK="/usr/bin/svnlook";    //modify svnlook path
$TABLE="p_upload";

$PROJECTS=array(
	'{{projectId}}'=>'{{svnProjectName}}'	     //{{svnProjectName}}
);

$INFO = getReposInfo();
$LISTS = getChangedList();
insertDb();



function insertDb() {
	global $DBHOST, $DBUSER, $DBPASS, $DBNAME, $INFO, $LISTS, $TABLE;
	$conn = mysql_connect($DBHOST, $DBUSER, $DBPASS);
	mysql_select_db($DBNAME, $conn);
	mysql_query("SET NAMES utf8");
	foreach($LISTS as $list) {
        $sql = " 
            REPLACE INTO %s (filename,author,updateTime,projectId,status,logMessage,timezone) 
            VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')
            ";
        $sql = sprintf($sql,
                        $TABLE,
                        mysql_escape_string($list['file']),
                        mysql_escape_string($INFO['author']),
                        mysql_escape_string($INFO['date']),
                        mysql_escape_string($list['projectId']),
                        mysql_escape_string($list['status']),
                        mysql_escape_string($INFO['logmessage']),
                        mysql_escape_string($INFO['timezone']));
		mysql_query($sql);
	}
}

function getProjectId($path) {
	global $PROJECTS;
	foreach($PROJECTS as $key => $value) {
		$pattern='&^'.$value.'/&';
		if (preg_match($pattern, $path)) return $key;
	}
	return 0;
}

function getReposInfo()
{
	global $REPOS, $REV, $SVNLOOK;
	$info = `$SVNLOOK info -r "$REV" "$REPOS"`;
	$tmps = explode("\n", $info);
	$author = trim($tmps[0]);
	$dates = explode(' ', $tmps[1]);
	$date = $dates[0].' '.$dates[1];
	$timezone=$dates[2];
	
	unset($tmps[0]);unset($tmps[1]);unset($tmps[2]);

	$logmessage = trim(join("\n", $tmps));

	return array(
		'author'=>$author,
		'logmessage'=>filterLog($logmessage),
		'date'=>$date,
		'timezone'=>$timezone
	);
}

function getChangedList()
{
	global $REPOS, $REV, $SVNLOOK, $PROJECTS;
	$changed = `$SVNLOOK changed -r "$REV" "$REPOS"`;
	`echo "$changed" >> /tmp/c.log`;
	$changeds = explode("\n", $changed);
	$lists = array();
	foreach($changeds as $line) {
		if (trim($line)=='') continue;
		$tmps = explode(' ', trim($line));
		$file = $tmps[count($tmps)-1];
		$status=$tmps[0];
		$projectId = getProjectId($file);
		$lists[]=array('file'=>$file, 'status'=>$status, 'projectId'=>$projectId);

	}
	return $lists;
}

function filterLogCallback($matches) {
	$ord = substr($matches[0], 2);
	return chr($ord);
}

function filterLog($name) {
	$pattern = "#\?\\\\\d{3}#";
	return preg_replace_callback($pattern, "filterLogCallback", $name);
}
